Can a single if-else
statement choose one of three options?
No. An if-else
statement makes
a choice between two options.
To make a three-way choice,
a nested if is used.
This is where an if-else
statement is
part of a the true-branch (or false-branch) of another if-else
statement.
So the nested if-else
will execute only when the outer if-else
has already made a choice
between two branches.
Here is a program fragment that makes a choice
of one of the three suffixes.
String suffix;
int count=0; // count is the number of integers added so far.
// count+1 is the next integer to read
. . . .
if ( count+1 )
suffix = "nd";
else
if ( count+1 ) // false-branch of first if
suffix = "rd"; // false-branch of first if
else // false-branch of first if
suffix = "th"; // false-branch of first if
System.out.println( "Enter the " +
(count+1) + suffix + " integer (enter 0 to quit):" );
The false-branch of the first if
statement consists
of another entire if
statement.
Fill in the blanks so that: